import { getCategoryApi } from '../../api/nav.js';
import { getProductsApi } from '../../api/product.js';

Page({
  data: {
    active: null,
    categoryList: [],
    productList: [],
    loading: false,
    pageNo: 0,
    notMoreData: false,
  },

  /** 获取分类 */
  async getCategory(id) {
    console.log(this.data.notMoreData);

    const res = await getCategoryApi();
    this.setData({
      categoryList: res,
      active: id ?? res[0]._id,
    });
    this.getProductList();
  },

  /** 获取产品列表 */
  async getProductList() {
    console.log(123123);

    if (this.data.notMoreData) return;
    try {
      this.setData({
        loading: true,
      });
      const res = await getProductsApi({
        size: this.data.pageNo,
        navid: this.data.active,
      });
      console.log('🚀 ~ getProductList ~ res ====> ', res);
      this.data.productList.push(...res);
      this.setData({
        notMoreData: !res.length,
        productList: this.data.productList,
      });
      console.log(this.data.productList);
    } catch (error) {
      console.log(error);
    } finally {
      this.setData({
        loading: false,
      });
    }
  },

  /** tabs当前激活的tab变化事件处理函数 */
  handleChange(e) {
    console.log('🚀 ~ handleChange ~ name ====> ', e);
    this.setData({
      active: e.detail.name,
      pageNo: 0,
      notMoreData: false,
      productList: [],
    });
    this.getProductList();
  },

  /** 页面上拉触底 */
  onReachBottom() {
    this.data.pageNo += 5;
    this.getProductList();
  },

  /** 页面加载 */
  onLoad(options) {
    this.getCategory(options.id);
  },
});
